package com.androidx.workmanager

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.work.OneTimeWorkRequest
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView3.setOnClickListener {
            startWorkManager()
        }
    }

    fun startWorkManager() {
        //构建单次运行的后台任务请求
        val request = OneTimeWorkRequest.Builder(WorkManagerTest::class.java).build()
        //构建周期性运行的后台任务请求, 为了降低设备的性能功耗
        val request1 =
            PeriodicWorkRequest.Builder(WorkManagerTest::class.java, 1, TimeUnit.SECONDS).build()
        // 系统在合适的时间调用两个后台任务
        WorkManager.getInstance(this).enqueue(request)
        WorkManager.getInstance(this).enqueue(request1)
    }
}